from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password,check_password
import re
import random
import string
import redis
# Create your views here.
class checkName(APIView):
    def get(self,request,username):
        if not username:
            return Response({'code':200,'msg':'用户名不能为空'})
        if not re.findall(r'[a-zA-Z][a-zA-Z0-9]{4,15}$',username):
            return Response({'code':400,'msg':'用户名不符合规定'})
        if Users.objects.filter(username=username).count()>0:
            return Response({'code':400,'msg':'用户名以重复'})
        return Response({'code':200,'msg':'用户名校验成功'})

class checkMobile(APIView):
    def get(self,request,mobile):
        if not mobile:
            return Response({'code':200,'msg':'手机号不能为空'})
        if not re.findall(r'1[3-9][0-9]{4,15}$',mobile):
            return Response({'code':400,'msg':'手机号不符合规定'})
        if Users.objects.filter(username=mobile).count()>0:
            return Response({'code':400,'msg':'手机号以重复'})
        return Response({'code':200,'msg':'手机号校验成功'})

class checkImage(APIView):
    def get(self,request,uuid):
        str_num=''.join(random.sample(string.ascii_letters+string.digits,4))
        r=redis.Redis(host="localhost",
        port=6379,
        db=0,)
        r.set(uuid,str_num,ex=5)
        r.close()
        cap=ImageCaptcha()
        img=cap.generate(str_num)
        return HttpResponse(content_type='image/png',content=img)

    def post(self,request,uuid):
        code1=request.data.get('code')
        r = redis.Redis(host="localhost",
                        port=6379,
                        db=0, )
        code2=r.get(uuid)
        r.close()
        if code2:
            aa=code2.decode()
        else:
            return Response({'code':400,'msg':'验证码已过期'})
        if aa.lower()!=code1.lower():
            return Response({'code':400,'msg':'验证码错误'})
        return Response({'code':200,'msg':'验证码校验成功'})

class Register(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        password2=request.data.get('password2')
        mobile =request.data.get('mobile')
        if not all([username,password,password2,mobile]):
            return Response({'code':400,'msg':'字段不完整'})
        if not mobile:
            return Response({'code': 400, 'msg': '手机号不可为空'})
        if not password != password2:
            return Response({'code':400,'msg':'两次输入的密码不一致'})
        pwd=make_password(password)
        Users.objects.create(
            username=username,password=pwd,mobile=mobile
        )
        return Response({'code':200,'msg':'注册成功'})
class Login(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        try:
          user=Users.objects.get(username=username)
        except Exception as e :
            print(e)
            return Response({'code':400,'msg':'用户不存在'})
        if not username:
            return Response({'code':400,'msg':'用户名不可为空'})
        if not check_password(password,user.password):
            return Response({'code':400,'msg':'密码不一致'})
        return Response({
            'code':200,
            'msg':'登录成功',
            'user':{
                'id':user.id,
                'username':user.username,
            }
        })





